package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/***
 * 监听秒杀商品库存的消息，在活动结束30分钟后进行同步
 */
@Component
@Slf4j
public class SeckillGoodsStockFromRedisToDbListener {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @RabbitListener(queues = "seckill_goods_dead_queue")
    public void seckillGoodsStockFromRedisToDb(Channel channel, Message message){
        //获取消息
        String time = new String(message.getBody());//时间段
        //获取消息的属性
        MessageProperties properties = message.getMessageProperties();

        long deliveryTag = properties.getDeliveryTag();
        try{
            //调用业务层方法，进行同步操作
            seckillGoodsService.seckillGoodsStockFromRedisToDb(time);

            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try{
                //异常处理
                channel.basicReject(deliveryTag,false);
            }catch (Exception e1){
                log.error("拒绝消息发生异常,秒杀商品的时间段为: " + time);
            }
        }
    }
}
